package com.haofengsoft.scce.common.client;

import java.util.List;
import java.util.Map;

import android.content.Context;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;
import com.haofengsoft.platform.utils.NetWorkUtil;
import com.haofengsoft.platform.utils.ToastUtil;
import com.haofengsoft.scce.LoadingDialog;
import com.haofengsoft.scce.common.config.ConstantConfig;
import com.haofengsoft.scce.common.security.SecurityUtil;

/**
 * Created by Administrator on 2014/10/6.
 */
public class VolleyManage {
    private static class VolleyToolBuilder {
        static VolleyManage _instance = new VolleyManage();
    }

    public static VolleyManage getInstance() {
        return VolleyToolBuilder._instance;
    }

    public VolleyManage() {

    }


    private LoadingDialog loadingDialog;
    private RequestQueue requestQueue = null;

    /**
     * @param context
     * @param content         加载dialog提示文字
     * @param head            网络连接请求头
     * @param params          Map参数
     * @param volleyInterface
     */
    public void methodPost(Context context, String content, String head, Map<String, Object> params, VolleyInterface volleyInterface) {
        if (NetWorkUtil.isNetworkConnected(context)) {
            if (null != content) {
                loadingDialog = new LoadingDialog(context, content);
                loadingDialog.show();
            }
            method(context, content, Request.Method.POST, head, params, volleyInterface);
        } else {
            VolleyBean bean = new VolleyBean();
            bean.setSuccess(false);
            bean.setContent("出现异常");
            volleyInterface.gainData(bean);
            //没有连接网络
            ToastUtil.TextToast(context, "网络连接不可用，请你稍后再试", Toast.LENGTH_LONG);
        }
    }

    /**
     * @param context         上下文
     * @param content         进度条文字
     * @param head            Url
     * @param params          Map参数
     * @param picList         图片
     * @param volleyInterface
     */
    public void methodPost(Context context, String content, String head, Map<String, Object> params, List<PictureInfo> picList, VolleyInterface volleyInterface) {
        if (NetWorkUtil.isNetworkConnected(context)) {
            if (null != content) {
                loadingDialog = new LoadingDialog(context, content);
                loadingDialog.show();
            }
            if (picList != null && picList.size() > 0) {
//                new UploadTask(context, content, head, params, picList, volleyInterface).execute();
            } else {
                method(context, content, Request.Method.POST, head, params, volleyInterface);
            }
        } else {
            VolleyBean bean = new VolleyBean();
            bean.setSuccess(false);
            bean.setContent("出现异常");
            volleyInterface.gainData(bean);
            //没有连接网络
            ToastUtil.TextToast(context, "网络连接不可用，请你稍后再试", Toast.LENGTH_LONG);
        }
    }


    private void method(Context context, String content, int method, String serverName, Map<String, Object> params, VolleyInterface volleyInterface) {
        try {
            if (requestQueue == null) {
                requestQueue = Volley.newRequestQueue(context.getApplicationContext());
            }
            String url = ConstantConfig.API_URL + serverName;
            String tagId = url;
//            params.put("classId", "C8B111C973D69AB364C01DDB66CE1B7A");
//            params.put("teacherId", "96");
//            params.put("sourceId", "3");
//            params.put("deviceNo", EquipmentUtil.deviceId(context));
//            params.put("version", "v" + EquipmentUtil.getVersionName(context));
            String jsonParam = JSON.toJSONString(params, true);
            System.out.println("参数：" + jsonParam);
//            System.out.println("参数值：" + jsonParam);
            //统一加密成二进制
            final byte[] paramByte = SecurityUtil.encryptByPublicKey(context, jsonParam);
            VolleyRequest request = new VolleyRequest(method, url, paramByte, BackInfo.class, new SuccessListener(tagId, content, volleyInterface), new WrongListener(tagId, content, volleyInterface));
//            request.wait(10000);
            request.setTag("VOLLEY_API_URL");

            requestQueue.add(request);
        } catch (Exception e) {
            if (null != content) {
                loadingDialog.dismiss();
            }
            ToastUtil.TextToast(context, "服务器忙，请你稍后再试", Toast.LENGTH_LONG);
            VolleyBean bean = new VolleyBean();
            bean.setSuccess(false);
            bean.setContent("出现异常");
            volleyInterface.gainData(bean);
        }
    }

    class SuccessListener implements Response.Listener<BackInfo> {
        String tagId;
        String content;
        VolleyInterface volleyInterface;

        SuccessListener(String tagId, String content, VolleyInterface volleyInterface) {
            this.tagId = tagId;
            this.content = content;
            this.volleyInterface = volleyInterface;
        }

        @Override
        public void onResponse(BackInfo backInfo) {
            if (null != content) {
                loadingDialog.dismiss();
            }
            if (null != requestQueue) {
                requestQueue.cancelAll(tagId);
            }
            VolleyBean bean = new VolleyBean();
            if (null == backInfo) {
                // 返回值异常
                bean.setSuccess(false);
                bean.setMessage("服务器忙！请您稍后再试");
            } else {
                if ("true".equals(backInfo.getResult())) {
                    bean.setSuccess(true);
                    bean.setContent(backInfo.getMsg());
                    System.out.println("正确返回结果" + backInfo.getMsg());
                    bean.setMessage("成功");
                } else {
                    bean.setSuccess(false);
                    bean.setMessage(backInfo.getMsg());
                }
            }
            volleyInterface.gainData(bean);
        }
    }

    class WrongListener implements Response.ErrorListener {
        String tagId;
        String content;
        VolleyInterface volleyInterface;

        WrongListener(String tagId, String content, VolleyInterface volleyInterface) {
            this.tagId = tagId;
            this.content = content;
            this.volleyInterface = volleyInterface;
        }

        @Override
        public void onErrorResponse(VolleyError volleyError) {
            if (null != content) {
                loadingDialog.dismiss();
            }
            if (null != requestQueue) {
                requestQueue.cancelAll(tagId);
            }
            String error = volleyError.toString();
            System.out.println("错误返回结果" + error);
            VolleyBean bean = new VolleyBean();
            bean.setSuccess(false);
            bean.setMessage("服务器忙！请您稍后再试");
            volleyInterface.gainData(bean);
        }
    }


}
